'use strict';

/* Services */

angular.module('myApp.Manager', ['myApp.MessageStore','myApp.ContactHandler']).
	factory("MessageManager", ['$rootScope','MessageStore','ContactHandler', '$http','$q',
        function ($rootScope,MessageStore,ContactHandler,$http,$q) {
            var groupPrefix = "G#";
            var personPrefix = "T#";

            function prefix(message, operation) {
                if (operation == 'send') {
                    message.from = personPrefix + message.from;
                    message.to = ($rootScope.isGroup ? groupPrefix : personPrefix) + message.to;
                    message.group = message.to.indexOf(groupPrefix) == 0;
                } else {
                    message.group = message.to.indexOf(groupPrefix) == 0;
                    message.from = message.from.substring(2);
                    message.to = message.to.substring(2);
                }
            };

            function messageSourceIsValid(message) {
                if (message.from.indexOf(groupPrefix) >= 0
                    || message.from.indexOf(personPrefix) >= 0) {
                    return true;
                }
                return false;
            }

            function isAtMessage(message){
                if(message == null || message.content == null){
                    return false;
                }
                return message.content.indexOf('atGroupMemberInfoList') > -1;
            }

            function saveMessage(message) {
                MessageStore.saveMessage(message);
            }

            function isCurrChatMsg(msg) {
                if (!$rootScope.currentChatObj) return false;
                if (msg.msgType) {//聊天消息
                    var chatObjIdentifier = msg.group ? msg.to : msg.from;
                    return $rootScope.currentChatObj.identifier == chatObjIdentifier;
                } else if (msg.commType) {//命令消息
                    return $rootScope.currentChatObj.identifier == msg.groupId;
                }
                return false;
            }

            function getMessages(contactIdentifier) {
                return MessageStore.getMessages(contactIdentifier);
            }
            function getAllMessage(){
            	return MessageStore.getAllMessage();
            }
            function saveAllMessage(messages){
            	MessageStore.saveAllMessage(messages);
            }
            //paramData : { msgId, notifyType，action,userIds}
            var queryChangInfoPromise = function (paramData) {
                var deferred = $q.defer();
                $http({
                    method: 'POST',
                    url: 'contact/queryChangeInfo.do',
                    data: $.param(paramData),
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                }).success(function (result) {
                    if (result.error) {
                        deferred.reject(result.error);
                    }
                    deferred.resolve(result);
                }).error(function () {
                    deferred.reject('查询变更信息失败!');
                });
                return deferred.promise;
            }

            function Text() {
                this.copyMsg = function (message) {
                    message.content = message.content;
                    message.imgcontent = util.compileExpression(message.content);
                    var msg = angular.copy(message);
                    msg.send = true;
                    return msg;
                };

                this.send = function (message) {
                    prefix(message, 'send');
                    return message;
                };

                this.receive = function (message) {
                    prefix(message, 'receive');
                    if(isAtMessage(message)){
                        var atObj = JSON.parse(message.content);
                        message.content = atObj.text;
                    }else{
                        message.content = message.content;
                    }
                    message.imgcontent = util.compileExpression(message.content);
                    message.avatar = ContactHandler.getContact(message.from).avatar;
                    message.fromName = ContactHandler.getContact(message.from).name;
                };
            }

            function Image() {
                this.copyMsg = function (message) {
                	var temArray = message.thumbContent.split(",");
                	var b = new Int8Array(temArray);
                	var bytearr = new Array(b.length);
                    for (var i = 0; i < b.length ; i++){
                        bytearr[i] = b[i];
                    }
                    message.thumbContent = bytearr;
                    
                    var msg = angular.copy(message);
                    msg.thumbContent = wsutil.generateImgUrl(bytearr);
                    msg.sourceURL = msg.mediaId;
                    msg.send = true;
                    return msg;
                };
                this.send = function (message) {
                    prefix(message, 'send');
                    return message;
                };
                this.receive = function (message) {
                    prefix(message, 'receive');
                    message.thumbContent = wsutil.generateImgUrl(message.thumbContent);
                    message.sourceURL = message.mediaId;
                    message.sendstats = 1;
                    message.avatar = ContactHandler.getContact(message.from).avatar;
                    message.fromName = ContactHandler.getContact(message.from).name;

                };
            }

            function Voice(){
                this.receive = function(message){
                    prefix(message, 'receive');
                    message.avatar = ContactHandler.getContact(message.from).avatar;
                    message.fromName = ContactHandler.getContact(message.from).name;
                }
            }

            function File() {
                this.copyMsg = function (message) {
                    var msg = angular.copy(message);
                    msg.thumbContent = window.pcWeb.apiAddress + "/api/service/file/downloadStream/" + message.mediaId + "?access_token=" + window.pcWeb.user.access_token;
                    msg.send = true;
                    return msg;
                };
                this.send = function (message) {
                    prefix(message, 'send');
                    return message;
                };
                this.receive = function (message) {
                    prefix(message, 'receive');
                    message.thumbContent = window.pcWeb.apiAddress + "/api/service/file/downloadStream/" + message.mediaId + "?access_token=" + window.pcWeb.user.access_token;
                    message.avatar = ContactHandler.getContact(message.from).avatar;
                    message.fromName = ContactHandler.getContact(message.from).name;
                };
            }

            return {
                11: new Text(),
                12: new Image(),
                13: new Voice(),
                18: new File(),
                messageSourceIsValid: messageSourceIsValid,
                saveMessage: saveMessage,
                isCurrChatMsg: isCurrChatMsg,
                saveAllMessage :saveAllMessage,
                getMessages: getMessages,
                getAllMessage: getAllMessage,
                queryChangInfoPromise: queryChangInfoPromise
            };
	}]);


